package com.kujawnode.web;

import com.github.pagehelper.PageInfo;
import com.kujawnode.model.TUser;
import com.kujawnode.model.TUserVO;
import com.kujawnode.query.UserQuery;
import com.kujawnode.result.R;
import com.kujawnode.service.UserService;
import jakarta.annotation.Resource;
import org.apache.ibatis.annotations.Delete;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @version 1.0
 * @Author kujaw
 * @Date 2025/7/10 20:22
 * @注释
 */
@RestController
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 获取登录人信息
     * @param authentication
     * @return
     */
    @GetMapping(value="/api/login/info")
    public R loginInfo(Authentication authentication){
        TUser tUser = (TUser) authentication.getPrincipal();
        return R.OK(tUser);
    }

    /**
     * 自动登录
     * @return
     */
    @GetMapping(value="/api/login/free")
    public R freeLogin(){
        return R.OK();
    }

    @GetMapping(value="/api/users")
    public R userPage(@RequestParam(value="current",required = false) Integer current){
        if(current == null){
            current = 1;
        }
        PageInfo<TUser> pageInfo = userService.getUserByPage(current);
        return R.OK(pageInfo);
    }

    @GetMapping(value="/api/user/{id}")
    public R getUserDetail(@PathVariable(value="id") Integer id){
        TUserVO tUser = userService.getUserDetail(id);
        return R.OK(tUser);
    }

    /**
     * 添加用户
     * @param userQuery
     * @return
     */
    @PostMapping(value="/api/user")
    public R addUser(UserQuery userQuery){
        int result = userService.addUser(userQuery);
        return result >= 1 ? R.OK() : R.FAIL();
    }

    /**
     * 编辑用户
     * @param userQuery
     * @return
     */
    @PutMapping(value="/api/user")
    public R updateUser(UserQuery userQuery){
        int result = userService.updateUser(userQuery);
        return result >= 1 ? R.OK() : R.FAIL();
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @DeleteMapping(value="/api/user/{id}")
    public R deleteUserById(@PathVariable(value="id") Integer id){
        int result = userService.deleteUserById(id);
        return result >= 1 ? R.OK() : R.FAIL();
    }

    @DeleteMapping(value="/api/user")
    public R batchDeleteUser(@RequestParam(value="ids")List<Integer> ids){
        int result = userService.batchDeleteUser(ids);
        return result >= ids.size() ? R.OK() : R.FAIL();
    }

    /**
     * 获取负责人信息
     * @return
     */
    @GetMapping(value="/api/owner")
    public R getOwner(){
        List<TUser> ownerList = userService.getOwner();
        return R.OK(ownerList);
    }
}
